<template>
    <div class="view">
        <nav-bar backgroundColor="#7bbcff" color="#fff" :title="examInfo.ExamName || ''">
            <div class="back" slot="left" @click="back">
                <i class="iconfont icon-fanhui"></i>
            </div>
            <div class="complete" slot="right" @click="complete">
                交卷
            </div>
        </nav-bar>
        <div class="question-list-index">
            <div class="index-title">
                <div class="text">答题卡</div>
                <div class="chart">
                    <div class="chart-label chart-complete">已答题</div>
                    <div class="chart-block chart-complete"></div>
                    <div class="chart-label chart-uncomplete">未答题</div>
                    <div class="chart-block chart-uncomplete"></div>
                </div>
            </div>
            <cube-scroll class="question-index-scroll" :data="questionList">
                <div class="index-body">
                    <div @click="showThisQuestion(index)" :class="{'item-complete':question.QuestionAnswer,'item-uncomplete':!question.QuestionAnswer}" class="index-item" v-for="(question,index) in questionList" :key="question.QuetionItem.id">
                        {{index+1}}
                    </div>
                </div>
            </cube-scroll>


        </div>
        <div class="question-body go-up" :class="{'flexible':isFlexible}">
            <cube-scroll class="question-scroll" style="width: 100vw;" ref="scroll" :options="{bounce:false}">
                <div class="current-question" v-if="questionList.length>0">
                    <div class="question-type">
                        {{currentQuestion.QuetionItem.TypeName}}:
                    </div>
                    <div class="question-text" v-html="(currentIndex+1)+'、'+currentQuestion.QuetionItem.QuestionContent"></div>
                    <cube-radio-group class="question-radio" v-show="currentQuestionType==='radio'" v-model="radioSelected">
                        <cube-radio v-for="option in  currentOption" :key="option" :option="option"></cube-radio>
                    </cube-radio-group>
                    <cube-checkbox-group class="question-check" v-show="currentQuestionType==='check'" v-model="checkSelect">
                        <cube-checkbox :hollow-style="true" v-for="option in  currentOption" :key="option" :option="option"></cube-checkbox>
                    </cube-checkbox-group>
                    <div class="question-others" v-show="currentQuestionType==='other'">
                        <image-finder ref="imageFinder" :uploadStatus="uploadStatus" @clickImg="clickImg" :count="1" @addImg="addImg" @delImg="delImg"></image-finder>
                    </div>
                    <div class="complete-answer" v-if="currentQuestion.QuestionAnswer">
                        <div class="answer-preview" v-if="currentQuestionType==='other'">
                            <div class="tips">提交答案：</div>
                            <img :src="currentQuestion.QuestionAnswer.Anwner">
                        </div>
                        <div class="answer-text" v-else>
                            <div class="tips">提交答案：</div>
                            {{currentQuestion.QuestionAnswer.Anwner}}
                        </div>
                    </div>
                </div>
                <div class="question-safe-area"></div>
            </cube-scroll>
            <div class="question-safe-gradient">
                <div class="circle-btn" v-if="!isFavorate && !isFlexible" :class="{'animated heartBeat':isLoop}" @click.stop="setFacorite">
                    <i class="iconfont icon-aixin1"></i>
                </div>
                <div class="circle-btn" :class="{'animated rubberBand':isFavorate}" v-if="isFavorate && !isFlexible" @click.stop="setFacorite">
                    <i class="iconfont icon-aixin"></i>
                </div>
            </div>
            <div class="answer-schedule" @click="showQuestionIndex">
                <circle-schedule :class="{'animated fadeIn':isFlexible}" v-if="questionList.length>0" class="answer-schedule-circle" :percent="percent" :size="80">
                    <div class="text">{{completeCount}}/{{questionList.length}}</div>
                </circle-schedule>
                <div class="tips" :class="{'animated fadeIn':isFlexible}" v-if="questionList.length>0">点击选题</div>
            </div>
        </div>
        <div class="question-footer go-up" :class="{'flexible':isFlexible}" style="background-color: rgba(0,0,0,0)">
            <div class="circle-shadow"></div>
        </div>
        <div class="question-footer go-down" :class="{'flexible':isFlexible}">
            <div class="question-action" @click="prevItem" :class="{'question-action-stop':currentIndex<1}">上一题</div>
            <div class="question-action" @click="nextItem" :class="{'question-action-stop':currentIndex>questionList.length-1}">{{currentIndex==questionList.length-1?'完成':'下一题'}}</div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";
    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";

    import NavBar from "@/components/aui/NavBar.vue";
    import CircleSchedule from "@/components/aui/CircleSchedule.vue";
    import ImageFinder from "@/components/aui/ImageFinder.vue";

    import CommonUnit from "@/unit/CommonUnit";

    @Component({
        components: {
            NavBar, CircleSchedule, ImageFinder
        }
    })
    export default class QuestionDetail extends Scene {
        private type: number | string = 0;
        private examInfo: object = {};
        private questionList: object[] = [];
        private currentIndex: number = 0;
        private packageId: number | "" = "";
        private grade: string = "";
        private lessonName: string = "";
        private letter: string[] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
        private answerList: object[] = [];
        private radioSelected: string = "";
        private checkSelect: string[] = [];
        private imgs: any[] = [];
        private uploadPictureList: File[] = [];
        private uploadStatus: any = {};
        private isFavorate: boolean = false;
        private isLoop: boolean = false;
        private loopTimer: number = 0;
        private isFlexible: boolean = false;

        private unCompleteCount = 0;
        private completeCount = 0;

        @State("UserStore")
        public user!: InterfaceUser;

        // @Watch("radioSelected")
        // public watchRadioSelected(newValue: string) {
        //     if (newValue !== "") {
        //         this.saveAnswer();
        //     }
        // }
        //
        // @Watch("checkSelect")
        // public watchCheckSelect(newValue: string) {
        //     if (newValue !== "") {
        //         this.saveAnswer();
        //     }
        // }


        private get currentQuestionType(): string {
            const type = (<any> this).currentQuestion.QuetionItem.TypeName;
            if (type === "单选题" || type === "选择题") {
                return "radio";
            } else if (type === "多选题") {
                return "check";
            } else {
                return "other";
            }
        }

        private get currentOption(): string[] {
            let currentRadioOption: string[] = [];
            for (let i = 0; i < (<any> this).currentQuestion.QuetionItem.OptionAmount; i++) {
                currentRadioOption.push(this.letter[i]);
            }
            return currentRadioOption;
        }

        private get currentQuestion(): object {
            return this.questionList[this.currentIndex];
        }

        private get percent(): number {
            return Math.abs((this.completeCount / this.questionList.length) * 100);
        };

        private setLoop(): void {
            if (!this.isFavorate) {
                this.loopTimer = setInterval(() => {
                    this.isLoop = true;
                    setTimeout(() => {
                        this.isLoop = false;
                    }, 1000);
                }, 3000);

            } else {
                clearInterval(this.loopTimer);
            }
        }

        private async saveAnswer(): Promise<any> {
            if (this.currentQuestionType === "check" || this.currentQuestionType === "radio") {
                let params: any = {
                    answer: (this.currentQuestionType === "check" ? this.checkSelect.join("") : this.radioSelected),
                    isComplete: (<any> this).currentQuestion.QuestionAnswer ? 1 : 0,
                    examId: this.packageId,
                    questionId: (<any> this).currentQuestion.QuetionItem.id
                };
                if (this.type === "2") {
                    params.examId = 0;
                    params.isComplete = 1;
                }

                Http.post(this.api.submitQuestion, CommonUnit.argumentWithUser(this.user, params));
            }
        }

        private findAnswerObj(questionIndex: number): object | boolean {
            for (let i = 0; i < this.answerList.length; i++) {
                if ((<any> this).answerList[i].index === questionIndex) {
                    return (<any> this).answerList[i];
                }
            }
            return false;
        }

        private back(): void {
            this.navigateBack();
        }

        private async complete(): Promise<any> {
            let toast = (<any> this).$createToast({
                txt: "正在提交考卷",
                time: 0
            }).show();
            try {
                let params: any = {examId: this.packageId ? this.packageId : 0};
                const submitRes = await Http.get(this.api.submitExam, CommonUnit.argumentWithUser(this.user, params));
                toast.hide();
                if (submitRes.Success) {
                    (<any> this).$createDialog({
                        type: "alert",
                        confirmBtn: {
                            text: "好的～知道了！",
                            active: true
                        },
                        onConfirm: () => {
                            this.navigateBack();
                        }
                    }, (createElement: any) => {
                        return [
                            createElement("div", {
                                "class": {
                                    "exam-title": true
                                },
                                slot: "title"
                            }, [
                                createElement("div", {
                                    "class": {
                                        [`exam-title-img exam-title-img-${CommonUnit.randomNumBoth(1, 4)}`]: true
                                    }
                                }),
                                createElement("p", `《${submitRes.Data.ExamInfo.ExamName}》已经完成`)
                            ]),
                            createElement("p", {
                                "class": {
                                    "exam-title-content": true
                                },
                                slot: "content"
                            }, `客观题得分:${submitRes.Data.UserExaming.Mark}`)
                        ];
                    }).show();
                } else {
                    (<any> this).$createToast({
                        mask: true,
                        type: "warn",
                        time: 1500,
                        txt: `题目列表获取错误:${submitRes.Message}`,
                        onTimeout: () => {
                            if (!CommonUnit.responseLoginVerification(submitRes)) {
                                this.navigateLoginPage();
                            }
                        }
                    }).show();
                }
            } catch (e) {
                toast.hide();
            }
        }

        private prevItem(): void {
            if (this.currentIndex > 0) {
                this.currentIndex--;
                this.initStatus();
            }
        }

        private nextItem(): void {
            this.initStatus();
            if (this.currentIndex < this.questionList.length - 1) {
                this.currentIndex++;
            } else {
                (<any> this).$createToast({
                    mask: true,
                    type: "correct",
                    time: 1500,
                    txt: `已经是最后一题了，请点击交卷获取考试结果`,
                }).show();
            }
        }

        private initStatus(): void {
            this.saveAnswer();
            clearInterval(this.loopTimer);
            if (this.type === "1") {
                this.getAllQuestionList();
            } else {
                this.getErrorQuestion();
            }
            this.isLoop = false;
            this.isFavorate = false;
            this.radioSelected = "";
            if (this.currentIndex < this.questionList.length - 1) {
                this.checkSelect = [];
                this.uploadStatus = {};
                (<any> this).$refs.imageFinder.refresh();
            }
            this.$nextTick(() => {
                (<any> this).$refs.scroll.refresh();
                (<any> this).$refs.scroll.scrollTo(0, 0);

                this.uploadStatus = {};
                this.setLoop();
            });
        }

        private mounted(): void {
            this.packageId = (<any> this).$route.query.packageId;
            this.type = String((<any> this).$route.query.type);
            this.grade = (<any> this).$route.query.grade;
            this.lessonName = (<any> this).$route.query.lessonName;
            if (this.type) {
                if (this.type === "1" && this.packageId > 0) {
                    setTimeout(() => {
                        this.setLoop();
                        this.getAllQuestionList();
                    }, 500);
                } else if (this.type === "2") {
                    setTimeout(() => {
                        this.getErrorQuestion();
                    }, 500);

                }
            } else {
                // console.log(this.type);
                this.navigateBack();
            }
        }

        private async getErrorQuestion(): Promise<any> {
            const errorQuestionRes = await Http.get(this.api.getMyWorngQuestions, CommonUnit.argumentWithUser(this.user, {grade: this.grade, lessonName: this.lessonName}));
            if (errorQuestionRes.Success) {
                const questionList = Object.assign(this.questionList, errorQuestionRes.Data.Questions);
                this.questionList = questionList;
                this.examInfo = errorQuestionRes.Data.ExamInfo;
            } else {
                (<any> this).$createToast({
                    mask: true,
                    type: "warn",
                    time: 1500,
                    txt: `题目列表获取错误:${errorQuestionRes.Message}`,
                    onTimeout: () => {
                        if (!CommonUnit.responseLoginVerification(errorQuestionRes)) {
                            this.navigateLoginPage();
                        }
                    }
                }).show();
            }
        }


        private async getAllQuestionList(): Promise<any> {
            const completeListRes = await Http.get(this.api.getQuestionListByPackageId, CommonUnit.argumentWithUser(this.user, {packageID: this.packageId, isComplete: 1}));
            const unCompleteCountListRes = await Http.get(this.api.getQuestionListByPackageId, CommonUnit.argumentWithUser(this.user, {packageID: this.packageId, isComplete: 0}));
            if (completeListRes.Success && unCompleteCountListRes.Success) {
                const allQuestionList = [...completeListRes.Data.Questions, ...unCompleteCountListRes.Data.Questions].sort((a, b) => {
                    return (<any> a).QuetionItem.id - (<any> b).QuetionItem.id;
                });
                this.questionList = allQuestionList;
                this.examInfo = completeListRes.Data.ExamInfo;
                this.unCompleteCount = unCompleteCountListRes.Data.UnCompleteCount;
                this.completeCount = completeListRes.Data.CompleteCount;
            } else {
                (<any> this).$createToast({
                    mask: true,
                    type: "warn",
                    time: 1500,
                    txt: `题目列表获取错误:${completeListRes.Message}||${unCompleteCountListRes.Message}`,
                    onTimeout: () => {
                        if (!CommonUnit.responseLoginVerification(completeListRes) || !CommonUnit.responseLoginVerification(unCompleteCountListRes)) {
                            this.navigateLoginPage();
                        }
                    }
                }).show();
            }
        }

        private clickImg(i: number): void {
            (<any> this).$createImagePreview({
                "imgs": this.imgs.map((item: any) => {
                    return item.blob;
                }),
                "initial-index": i
            }).show();
        }

        private addImg(imgs: string[], uploadPictureList: File[]): void {
            this.imgs = imgs;
            this.uploadPictureList = uploadPictureList;
            let params: object = {hash: this.imgs[0].hash, picFile: uploadPictureList[0], isComplete: 1, examId: this.packageId, questionId: (<any> this).currentQuestion.QuetionItem.id};
            params = CommonUnit.argumentWithUser(this.user, params);
            this.uploadStatus = {hash: this.imgs[0].hash, link: "", status: 0, progress: "上传中"};
            Http.upload(this.api.submitQuestion, params).then((res: any) => {
                this.uploadStatus = {hash: this.imgs[0].hash, link: res.Data.Answer, status: 1, progress: "完成"};
            });
        }

        private delImg(i: number): void {
            this.imgs.splice(i, this.imgs.length);
            this.uploadPictureList.splice(i, this.uploadPictureList.length);
        }

        private setFacorite(): void {
            Http.get(this.api.favoriteQuestion, CommonUnit.argumentWithUser(this.user, {flag: !this.isFavorate, questionId: (<any> this).currentQuestion.QuetionItem.id})).then((res) => {
                if (res.Success) {
                    this.isFavorate = !this.isFavorate;
                } else {
                    if (res.Message.indexOf("已经收藏") >= 0) {
                        this.isFavorate = !this.isFavorate;
                    } else {
                        (<any> this).$createToast({
                            mask: true,
                            type: "warn",
                            time: 1500,
                            txt: res.Message
                        }).show();
                    }
                }
            });
        }

        private showQuestionIndex(): void {
            this.isFlexible = !this.isFlexible;
        }

        private showThisQuestion(i: number): void {
            this.isFlexible = false;
            setTimeout(() => {
                this.currentIndex = i;
                this.$nextTick(() => {
                    this.initStatus();
                });
            }, 200);

        }

    }
</script>

<style scoped lang="stylus">
    .view
        height 100vh;
        background $theme-page-common-background-color;
        overflow hidden

    .question-list-index
        height calc(100vh - 150px - env(safe-area-inset-top));
        bottom 0;
        width 100vw;
        position fixed;
        z-index 0;
        padding 10px 0 25px 0;

        .question-index-scroll
            width 100%;
            padding: calc(10px + env(safe-area-inset-bottom)) 0 10px 0;

        .index-body
            display flex;
            flex-wrap wrap;
            position relative;
            padding 0 12px;
            justify-content space-between;

            .index-item
                width 52px;
                height 52px;
                line-height 52px;
                margin-bottom 6px;
                text-align center;
                border-radius 12px;
                color #fff;
                font-size 21px

                &.item-complete
                    background $theme-common-color

                &.item-uncomplete
                    background $theme-specific-color

        .index-title
            height 30px;
            padding 0 12px;
            display flex;
            justify-content space-between;
            color #333;
            font-size 13px;
            align-items center;

            .text
                font-size 18px;

            .chart
                width max-content;
                display flex;
                justify-content space-between;
                align-items center;
                flex-direction row-reverse;

                .chart-block
                    width 11px;
                    height 11px;
                    border-radius 11px;


                    &.chart-complete
                        background $theme-common-color;
                        margin-left 15px;

                    &.chart-uncomplete
                        background $theme-specific-color;
                        margin-left 15px;

                .chart-label
                    font-size 13px;
                    margin-left 4px;

                    &.chart-complete
                        color $theme-common-color;

                    &.chart-uncomplete
                        color $theme-specific-color;


    .complete
        color #fff;
        width 58px;
        height 30px;
        text-align center;
        line-height 28px !important;
        border 1px solid rgba(255, 255, 255, .4);
        border-radius 32px;
        margin-top 7px;

    .circle-shadow, .answer-schedule

        background #fff;
        border-radius 90px;
        margin-top -50px
        padding 5px;
        bottom -40px;
        left 50%;
        margin-left -45px;
        width 88px;
        height 88px;
        position absolute;

    .question-body
        margin-top calc(44px + env(safe-area-inset-top));
        width 100vw;
        margin-bottom 50px;
        height calc(100vh - 44px - 50px - env(safe-area-inset-top) - env(safe-area-inset-bottom));
        /*box-shadow 0 0 10px 0 #ccc;*/
        box-shadow 0 15px 10px -15px #ccc;
        position absolute;
        z-index 12;
        background #fff;


        .answer-schedule
            z-index 20;
            bottom -45px;
            display flex;
            justify-content center;
            align-items center;

            .answer-schedule-circle
                .text
                    font-size 13px;
                    text-align center;
                    display block;
                    width 100%;
                    height 80px;
                    line-height 75px;

            .tips
                display block;
                width 100%;
                left 0;
                font-size 10px;
                margin-top 12px;
                text-align center;
                position absolute;


    .question-footer
        height 50px;
        box-sizing content-box;
        position fixed;
        bottom 0;
        left 0;
        right 0;
        display flex;
        justify-content space-between;
        align-items center;
        padding 0 10px env(safe-area-inset-bottom) 10px;
        background $theme-page-common-background-color;

        .circle-shadow
            box-shadow 0 0 10px 0 #ccc;
            top 50px;
            height 45px;
            border-radius 0 0 90px 90px;
            position absolute;
            z-index -100;


        .question-action
            width 110px;
            height 35px;
            text-align center;
            line-height 35px;
            border-radius 35px;
            background $theme-contrast-color;
            color #fff;

        .question-action-stop
            opacity .3;

    .question-safe-gradient
        background: #fff;
        background: linear-gradient(rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
        position absolute;
        bottom 0;
        height 45px;
        width 100%;
        z-index 1;
        display flex;
        padding 5px 10px;
        flex-direction row-reverse;
        align-items center;

        .circle-btn
            background rgba(255, 255, 255, .3);
            width 35px;
            height 35px;
            border-radius 35px;
            color $theme-advancing-color;
            line-height 35px;
            text-align center;
            margin-top -20px;
            margin-right 10px;

            i
                font-size 21px;
                display block;
                line-height 35px;


    .question-safe-area
        height 45px;

    .current-question
        padding 10px;


        .question-type
            height 22px;
            line-height 22px

        .question-text
            padding-top 20px;
            font-size 15px;
            line-height 2;

            >>> img
                display block !important;
                width auto !important;
                max-width 100% !important;
                height auto !important;
                margin auto !important;
                float none !important;

            >>> table
                margin 10px 0;
                border 1px solid #ddd !important;
                font-size 14px !important;

            >>> td
                border 1px solid #ddd !important;
                vertical-align middle !important;


        .question-radio, .question-check
            display flex;
            flex-direction row;
            justify-content space-between;
            margin-top 20px;
            font-size 20px;
            color #fff;

            &:before, &:after
                display none;

            >>> .cube-radio-wrap
                &:after
                    display none;

            >>> .cube-checkbox-wrap
                &:after
                    display none;

            .question-radio-item
                flex 1;
                text-align left;

        .question-others
            margin-top 20px;


    .complete-answer
        margin-top 10px;
        font-size 15px;
        color #333;

        img
            margin-top 10px;
            max-width 150px;
            width auto
            height auto;

        .tips
            margin-top 20px;
            line-height 24px;
            font-size 13px;
            color #666;


    .go-up, .go-down
        transition transform .5s ease-in-out;

    .flexible.go-up
        transform translateY(calc(135px - 100vh + env(safe-area-inset-top)))

    .flexible.go-down
        transform translateY(100%);
        opacity .1;
</style>
